package com.ww.springboot.boot.thread.study.base.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-06-10 17:47
 */
public class Lock响应中断 {

    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread(() -> {
            lock.lock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
                System.out.println("thread释放锁-----");
            }
        });
        thread.start();
        Thread.sleep(1000);

        Thread thread1 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println("------------lock进入锁--------");
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("------------lock释放锁--------");
                lock.unlock();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
            try {
                System.out.println("------------lockInterruptibly进入锁--------");
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("------------lockInterruptibly释放锁--------");
                lock.unlock();
            }
        });

        thread1.start();
        thread2.start();

        Thread.sleep(1000);

        System.out.println("--------thread1中断----");
        //lockInterruptibly()响应中断 --可以终止获取锁 --这种更好 等不到锁 就放弃获取
        thread1.interrupt();
        //lock不响应中断 ---中断会被延迟到获取锁执行阶段----这种不好 一直等待锁，获取到后立马又被中断
        System.out.println("--------thread2中断----");
        thread2.interrupt();
    }
}
